import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { logout as logoutApi } from '../api/serverApi'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('access-key') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('user-info') || 'null'))
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const username = computed(() => userInfo.value?.username || '')
  
  // 方法
  const setToken = (newToken) => {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('access-key', newToken)
    } else {
      localStorage.removeItem('access-key')
    }
  }
  
  const setUserInfo = (info) => {
    userInfo.value = info
    if (info) {
      localStorage.setItem('user-info', JSON.stringify(info))
    } else {
      localStorage.removeItem('user-info')
    }
  }
  
  const login = (tokenValue, userInfoValue) => {
    setToken(tokenValue)
    setUserInfo(userInfoValue)
  }
  
  const logout = async () => {
    try {
      // 调用后端logout接口清除Redis中的用户信息
      await logoutApi()
    } catch (error) {
      console.error('调用后端logout接口失败:', error)
      // 即使后端调用失败，也要清除前端的登录状态
    }
    
    // 清除前端的登录状态
    setToken('')
    setUserInfo(null)
  }
  
  const updateToken = (newToken) => {
    setToken(newToken)
  }
  
  return {
    // 状态
    token,
    userInfo,
    // 计算属性
    isLoggedIn,
    username,
    // 方法
    login,
    logout,
    updateToken,
    setToken,
    setUserInfo
  }
})